/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.maze.behaviours;

import java.util.ArrayList;
import org.maze.Maze;
import org.maze.individual.Individual;

/**
 *
 * @author Thomas
 */
public class OutOfDeadEndImprovementBehaviour extends AbstractImprovementBehaviour implements IImprovementBehaviour{

    public byte[] improve(Individual individual) throws Exception{
        ArrayList<Integer> path = individual.getPath();
        if(path.isEmpty() || path.size() == 1)
            return individual.getGenome();
        Maze maze = Maze.getInstance();
        int posx = path.get(path.size()-1)%Maze.SIZE;
        int posy = path.get(path.size()-1)/Maze.SIZE;
        int av = maze.getAvailablePath(posx, posy);
        if(av == 1){
            ArrayList<Integer> crossRoad = new ArrayList<Integer>();
            ArrayList<Integer> genPosition = new ArrayList<Integer>();
            int i = 0;
            // we look if there is several way avalable at starting position
           for(int j = 0; j<path.size()-2; j++){
                int p = path.get(j);
                posx = p%Maze.SIZE;
                posy = p/Maze.SIZE;
                // search if their is more than one path available
                if(maze.getAvailablePath(posx, posy)>2){
                    crossRoad.add(p);
                    genPosition.add(i);
                }
                i++;
            }
            if(crossRoad.isEmpty())
                return individual.getGenome();
            int a = rand.nextInt(crossRoad.size());
            int positionInGenome = genPosition.get(a);
            int choosenCross = crossRoad.get(a);
            int val=choosenCross;
            int dir = 0;
            byte[] genome = individual.getGenome();
            do{
                dir = rand.nextInt(4);
                if(dir == Individual.EAST)
                    val+=1;
                else if(dir == Individual.WEST)
                    val-=1;
                else if(dir == Individual.SOUTH)
                    val+=Maze.SIZE;
                else if(dir == Individual.NORTH)
                    val-=Maze.SIZE;
            }while(path.get(positionInGenome-1)==val || path.get(positionInGenome+1)==val || val<0);
            byte[] r = new byte[1];
            r[0]=(byte)dir;
            int size = path.size()-positionInGenome;
            genome = this.replace(genome, positionInGenome, size, r);
            return genome;
        }else{
            return individual.getGenome();
        }

    }

}
